import React, { useState } from 'react';

import { InputItem, Modal, Progress } from 'antd-mobile';

import filelistType from '@/assets/entry/filelistType.png';
import IconFont from '@/components/IconFont';
import FileUploadMobile from '@/components/Mobile/FileUploadMobile';
import add from '@/components/Mobile/FileUploadMobile/icon-add.png';
import { getFileType } from '@/pages/EntryManage/utils';
import { formatEllipsis } from '@/pages/Mail/utils';

import styles from './index.less';

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

// 手机端入职指引第二步材料表单项
const MaterialItem = React.forwardRef((props, ref) => {
    const {
        onChange,
        value,
        inputType,
        uploadTip,
        uploadFormatTip,
        uploadCountLimit,
        uploadFormatLimit,
        materialCode
    } = props;
    const uploadPros = {
        fileSize: 10
    };

    const [isShowUploadBtn, setIsShowUploadBtn] = useState(true);
    if (inputType === 0) {
        return <InputItem placeholder="请输入" ref={ref} maxLength={200} clear onChange={onChange} value={value} />;
    }

    const [previewImage, setPreviewImage] = useState();
    const [modalTitle, setModalTitle] = useState();
    const [visible, setVisible] = useState(false);

    const handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setVisible(true);
        setPreviewImage(file.url || file.preview);
    };

    if (inputType === 1) {
        return (
            <>
                <FileUploadMobile
                    showPreviewFile
                    accept="image/*"
                    ref={ref}
                    onChange={e => {
                        const { allFileList } = e;
                        if (allFileList?.length >= uploadCountLimit) {
                            setIsShowUploadBtn(false);
                        } else {
                            setIsShowUploadBtn(true);
                        }
                        if (onChange) {
                            onChange(e);
                        }
                    }}
                    value={value}
                    categoryCode={materialCode}
                    className={styles.uploadItemWrap}
                    checkFileSize={uploadPros.fileSize}
                    checkFileSizeMsg={`文件大小不能超过${uploadPros.fileSize}MB！`}
                    checkFileType={uploadFormatLimit && uploadFormatLimit?.replace(/\//g, ',')}
                    checkFileTypeMsg={`只支持${uploadFormatLimit}文件`}
                    customUploadList={(filelist = [], handleRemove) => (
                        // 自定义渲染列表
                        <ul className={styles.fileListWrap}>
                            {filelist?.length > 0 ? (
                                filelist.map(item => {
                                    const { percent, status, name, uid } = item;
                                    const fileName2Array = name.split('.') || [];
                                    // console.log(item, 'fileItem');
                                    return (
                                        <li key={uid} className={status === 'error' ? styles.error : ''}>
                                            {(status === 'done' || status === undefined) && (
                                                <>
                                                    <span>
                                                        <img
                                                            alt=""
                                                            src={filelistType}
                                                            style={{ marginRight: 8, width: 40 }}
                                                        />
                                                        {fileName2Array.length > 0
                                                            ? `${formatEllipsis(fileName2Array[0], 14, 8, 4)}.${
                                                                  fileName2Array[1]
                                                              }`
                                                            : name}
                                                    </span>
                                                    <span>
                                                        {getFileType(name) === 'image' && (
                                                            <IconFont
                                                                icon="eye"
                                                                style={{
                                                                    marginRight: 14,
                                                                    fontSize: 20,
                                                                    color: '#858B9B'
                                                                }}
                                                                onClick={() => {
                                                                    setModalTitle(name);
                                                                    handlePreview(item);
                                                                }}
                                                            />
                                                        )}

                                                        <IconFont
                                                            icon="close-circle"
                                                            theme="filled"
                                                            style={{ fontSize: 17, color: '#858B9B' }}
                                                            onClick={() => handleRemove(item)}
                                                        />
                                                    </span>
                                                </>
                                            )}
                                            {status === 'uploading' && (
                                                <>
                                                    <img
                                                        alt=""
                                                        src={filelistType}
                                                        style={{ marginRight: 8, width: 40 }}
                                                    />
                                                    <Progress
                                                        percent={percent}
                                                        position="normal"
                                                        appearTransition
                                                        style={{ width: '100%' }}
                                                    />
                                                </>
                                            )}
                                            {status === 'error' && (
                                                <>
                                                    <span>
                                                        <img
                                                            alt=""
                                                            src={filelistType}
                                                            style={{ marginRight: 8, width: 40 }}
                                                        />
                                                        {fileName2Array.length > 0
                                                            ? `${formatEllipsis(fileName2Array[0], 14, 8, 4)}.${
                                                                  fileName2Array[1]
                                                              }`
                                                            : name}
                                                    </span>
                                                    <span>
                                                        <IconFont
                                                            icon="close-circle"
                                                            theme="filled"
                                                            style={{ fontSize: 17, color: '#858B9B' }}
                                                            onClick={() => handleRemove(item)}
                                                        />
                                                    </span>
                                                </>
                                            )}
                                        </li>
                                    );
                                })
                            ) : (
                                <li />
                            )}
                        </ul>
                    )}
                >
                    {isShowUploadBtn === true ? (
                        <div className={styles.uploadButton}>
                            <img alt="" src={add} width="20" height="20" style={{ marginRight: 6 }} />
                            上传文件
                        </div>
                    ) : (
                        <div></div>
                    )}
                </FileUploadMobile>

                {isShowUploadBtn && (
                    <ul className={styles.tipWrap}>
                        <li>{uploadTip}</li>
                        <li>{uploadFormatTip}</li>
                    </ul>
                )}
                {/* UI和UE都没提供 */}
                <Modal
                    wrapClassName={styles.popModalWrap}
                    title={modalTitle}
                    closable={false}
                    visible={visible}
                    transparent
                    afterClose={() => {
                        setPreviewImage();
                    }}
                    onClose={() => {
                        setVisible(false);
                    }}
                    footer={[
                        {
                            text: '关闭',
                            onPress: () => {
                                setVisible(false);
                            }
                        }
                    ]}
                >
                    <div className={styles.modalBodyContainer}>
                        <img alt="" style={{ width: '100%' }} src={previewImage} />
                    </div>
                </Modal>
            </>
        );
    }
    return null;
});

export default MaterialItem;
